package dhy.com.container;

import dhy.com.exception.RpcContainerException;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
  * <P>
 *     容器类的具体实现子类
  * </P>
 * @author zdh
 */
public class RpcContainerImpl implements RpcContainer {
    /**
     * 客户端容器--存放Client注解标注的接口下所有方法名和方法的映射关系
     */
    private static final Map<String, Class> cilent_container = new ConcurrentHashMap<>();

    /**
     * 服务端容器---存放Server注解标注的方法的方法名和方法的映射
     */
    private static final Map<String,Class> server_container=new ConcurrentHashMap<>();


    public static Class getInstanceFromClient(String className) {
        return cilent_container.get(className);
    }


    public static Class getInstanceFromServer(String className) {
        return server_container.get(className);
    }

    public static Collection<Class> getAllClientInstances()
    {
        Collection<Class> values = cilent_container.values();
        return values;
    }

    @Override
    public void putInstanceIntoClient(Class instance) throws RpcContainerException {
        Object res = cilent_container.putIfAbsent(instance.getSimpleName(), instance);
        if (res != null) {
            throw new RpcContainerException("Client容器中Client实例存在多个");
        }
    }

    @Override
    public void putInstanceIntoServer(Class instance) throws RpcContainerException {
        Object res = server_container.putIfAbsent(instance.getSimpleName(), instance);
        if (res != null) {
            throw new RpcContainerException("Server容器中method实例存在多个");
        }
    }

    /**
     * <p>
     * 销毁rpc容器
     * </p>
     */
    public void destoryRpcContainer() {
        cilent_container.entrySet().stream().forEach(instance -> {
            cilent_container.remove(instance.getKey());
        });
        server_container.entrySet().stream().forEach(instance -> {
            server_container.remove(instance.getKey());
        });
    }
}
